<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/news' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.newsId" placeholder="输入新闻编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model="formInline.userId" placeholder="输入发布用户编号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input size="small" v-model="formInline.newsTitle" placeholder="输入新闻标题"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="formInline.newsType" placeholder="请选择">
          <el-option label="全部" value></el-option>
          <el-option
            v-for="type in typeList"
            :label="type.key"
            :value="type.typeName"
            :key="type.typeName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%;"
    >
      <el-table-column sortable prop="newsId" label="新闻编号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column sortable prop="userId" label="发布用户编号" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userIdentity" label="用户身份" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userName" label="用户姓名" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newsTitle" label=" 新闻标题" width="140" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newsType" label="新闻类型" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column
        sortable
        prop="newsCollection"
        label="点赞人数"
        width="120"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        sortable
        prop="newsIntegral"
        label="阅读积分"
        min-width="80"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column sortable prop="newsWatch" label="观看人数" min-width="80" show-overflow-tooltip></el-table-column>
      <el-table-column prop="newsTime" label="创建时间" width="180" show-overflow-tooltip>
        <template slot-scope="scope">
          <div>{{scope.row.newsTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="newsState" label="审核状态" min-width="80">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.newsState==1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editType(scope.$index, scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row,0)">预览</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="60%"
      @click="closeDialog('editForm')"
    >
      <template v-if="editType==0">
        <el-form label-width="100px" :model="editForm" ref="editForm">
          <el-form-item label="新闻编号">
            <el-input
              size="small"
              v-model="editForm.newsId"
              auto-complete="off"
              placeholder="请输入新闻编号"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="发布用户编号">
            <el-input
              size="small"
              v-model="editForm.userId"
              auto-complete="off"
              placeholder="请输入发布用户编号"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="用户身份">
            <el-input
              size="small"
              v-model="editForm.userIdentity"
              auto-complete="off"
              placeholder="请输入用户身份"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input
              size="small"
              v-model="editForm.userName"
              auto-complete="off"
              placeholder="请输入用户姓名"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="新闻标题">
            <el-input
              size="small"
              v-model="editForm.newsTitle"
              auto-complete="off"
              placeholder="请输入新闻标题"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="新闻类型">
            <el-input
              size="small"
              v-model="editForm.newsType"
              auto-complete="off"
              placeholder="请输入新闻类型"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="点赞人数">
            <el-input
              size="small"
              v-model="editForm.newsCollection"
              auto-complete="off"
              placeholder="请输入点赞人数"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="阅读积分">
            <el-input
              size="small"
              v-model="editForm.newsIntegral"
              auto-complete="off"
              placeholder="请输入阅读积分"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="观看人数">
            <el-input
              size="small"
              v-model="editForm.newsWatch"
              auto-complete="off"
              placeholder="请输入观看人数"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input
              size="small"
              v-model="editForm.newsTime"
              auto-complete="off"
              placeholder="请输入创建时间"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="新闻图片">
            <img v-for="(url, index) in editForm.newsImg" :key="index" :src="url" width="100" height="100" style="margin:20px;"/>
          </el-form-item>
          <el-form-item label="新闻内容">
            <el-input
              size="small"
              v-html="editForm.newContent"
              auto-complete="off"
              placeholder="请输入新闻内容"
              disabled
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template v-else-if="editType==2">
        <el-form label-width="100px" :model="editForm" ref="editForm" :rules="rules">
          <el-form-item label="新闻标题" prop="newsTitle">
            <el-input v-model="editForm.newsTitle"></el-input>
          </el-form-item>
          <el-form-item label="新闻类型" prop="newsType">
            <el-select v-model="editForm.newsType" placeholder="请选择新闻类型" style="width: 100%;">
              <el-option
                v-for="type in typeList"
                :label="type.key"
                :value="type.typeName"
                :key="type.typeName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="新闻时间" required>
            <el-form-item prop="newsTime">
              <el-date-picker
                type="datetime"
                placeholder="选择日期"
                v-model="editForm.newsTime"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="收藏人数" prop="newsCollection">
            <el-input v-model="editForm.newsCollection" type="number"></el-input>
          </el-form-item>
          <el-form-item label="新闻积分" prop="newsIntegral">
            <el-input v-model="editForm.newsIntegral" type="number"></el-input>
          </el-form-item>
          <el-form-item label="观看人数" prop="newsWatch">
            <el-input v-model="editForm.newsWatch" type="number"></el-input>
          </el-form-item>
          <el-form-item label="新闻图片">
            <el-upload
              action="/apis/user/uploadImg"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item label="新闻内容" prop="newContent">
            <Editor v-model="editForm.newContent" />
          </el-form-item>
        </el-form>
        <div slot="footer" style="margin-top: 20px;" class="dialog-footer">
          <el-button size="small" @click="closeDialog('edit')">取消</el-button>
          <el-button
            size="small"
            type="primary"
            :loading="loading"
            class="title"
            @click="submitForm('editForm')"
          >保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Comm/Pagination";
import {
  typeListAll,
  newsList,
  newsState,
  newsSave,
  newsUpdate,
  newsDelete
} from "../../ajax/index";
import Editor from "../Comm/editor";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      dialogVisible: false,
      dialogImageUrl: "",
      title: "预览",
      editForm: {
        newsId: "",
        userId: "",
        userIdentity: "",
        newsState: "",
        newsTitle: "",
        newsType: "",
        newsCollection: "",
        newsIntegral: "",
        newsWatch: "",
        newsTime: "",
        newContent: "",
        userName: "",
        newsImg: []
      },
      editTypa: 0,
      formInline: {
        page: 1,
        limit: 10,
        newsId: "",
        userId: "",
        newsType: "",
        newsTitle: ""
      },
      listData: [], //用户数据
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      typeList: [],
      rules: {
        newsTitle: [
          { required: true, message: "请输入新闻标题", trigger: "blur" }
        ],
        newsType: [
          { required: true, message: "请选择新闻类型", trigger: "blur" }
        ],
        newContent: [
          { required: true, message: "请输入新闻内容", trigger: "blur" }
        ]
      }
    };
  },
  // 注册组件
  components: {
    Pagination,
    Editor
  },
  created() {
    this.gettypeListAll();
    this.getdata(this.formInline);
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取公司列表
    getdata(parameter) {
      this.loading = true;
      newsList(parameter)
        .then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$message({
              type: "info",
              message: res.msg
            });
            this.listData = [];
            this.pageparm.currentPage = 1;
            this.pageparm.pageSize = 10;
            this.pageparm.total = 0;
          } else {
            this.listData = res.data;
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page;
            this.pageparm.pageSize = this.formInline.limit;
            this.pageparm.total = res.count;
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error("菜单加载失败，请稍后再试！");
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.getdata(this.formInline);
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline);
    },
    //显示编辑界面
    handleEdit: function(index, row, type) {
      if (row != undefined && row != "undefined") {
        this.editType = type;
        if (type == 0) {
          this.title = "预览";
          this.editForm = JSON.parse(JSON.stringify(row));
          this.editForm.newsTime = this.$comm.timestampToTime(
            this.editForm.newsTime
          );
        } else {
          this.title = "修改新闻";
        }
      } else {
        this.title = "添加新闻";
        this.editType = 2;
        this.editForm.newsId = "";
        this.editForm.newsTitle = "";
        this.editForm.newsType = "";
        this.editForm.newsCollection = "";
        this.editForm.newsIntegral = "";
        this.editForm.newsTime = "";
        this.editForm.newsWatch = "";
        this.editForm.newContent = "";
        this.editForm.newsImg = [];
      }
      this.editFormVisible = true;
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        this.editForm.newsImg = this.editForm.newsImg.map(item => item.url);
        if (valid) {
          [newsSave, newsUpdate]
            [this.editForm.newsId ? 1 : 0](this.editForm)
            .then(res => {
              this.editFormVisible = false;
              this.loading = false;
              if (res.code) {
                this.getdata(this.formInline);
                this.$message({
                  type: "success",
                  message: "新闻保存成功！"
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.editFormVisible = false;
              this.loading = false;
              this.$message.error("新闻保存失败，请稍后再试！");
            });
        } else {
          return false;
        }
      });
    },
    // 删除新闻
    deleteUser(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          newsDelete({
            newsId: row.newsId
          })
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "新闻已删除!"
                });
                this.getdata(this.formInline);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.loading = false;
              this.$message.error("新闻删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 关闭编辑、增加弹出框
    closeDialog(formName) {
      this.editFormVisible = false;
      this.$refs[formName].resetFields();
    },
    gettypeListAll() {
      typeListAll()
        .then(res => {
          if (res.code) {
            this.typeList = res.data;
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error("分类加载失败，请稍后再试！");
        });
    },
    // 修改type
    editType: function(index, row) {
      this.loading = true;
      let parm = {
        newsId: "",
        newsState: ""
      };
      parm.newsId = row.newsId;
      let state = row.newsState;
      if (state == "1") {
        parm.newsState = "0";
      } else {
        parm.newsState = "1";
      }
      // 修改状态
      newsState(parm).then(res => {
        this.loading = false;
        if (res.cpde == 0) {
          this.$message({
            type: "info",
            message: res.msg
          });
        } else {
          this.$message({
            type: "success",
            message: "状态修改成功"
          });
          this.getdata(this.formInline);
        }
      });
    },
    handleRemove(file, fileList) {
      for (const i in this.editForm.newsImg) {
        if (this.editForm.newsImg[i].key === file.uid) {
          this.editForm.newsImg.splice(i, 1);
        }
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      if (file.response.code) {
        this.editForm.newsImg.push({
          url: file.response.url,
          uid: file.uid
        });
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error("上传图片只能是 JPG或png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return (isJPG || isPng) && isLt2M;
    }
  }
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>